package com.bsj.pay.util;

import org.apache.commons.codec.binary.*;
import javax.crypto.spec.*;
import javax.crypto.*;
import java.security.*;

public class GoogleCode {
	public static final int SECRET_SIZE = 10;
	public static final String SEED = "g8GjEvTbW5oVSV7avLBdwIHqGlUYNzKFI7izOF8GwLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx";
	public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";
	int window_size;

	public GoogleCode() {
		this.window_size = 3;
	}

	public void setWindowSize(final int s) {
		if (s >= 1 && s <= 17) {
			this.window_size = s;
		}
	}

	public static Boolean authcode(final String codes, final String savedSecret) {
		final long code = Long.parseLong(codes);
		final long t = System.currentTimeMillis();
		final GoogleCode ga = new GoogleCode();
		ga.setWindowSize(15);
		final boolean r = ga.check_code(savedSecret, code, t);
		return r;
	}

	public static String genSecret(final String name) {
		final String secret = generateSecretKey();
		getQRBarcodeURL(name, "testhost", secret);
		return secret;
	}

	public static String generateSecretKey() {
		SecureRandom sr = null;
		try {
			sr = SecureRandom.getInstance("SHA1PRNG");
			sr.setSeed(Base64
					.decodeBase64("g8GjEvTbW5oVSV7avLBdwIHqGlUYNzKFI7izOF8GwLDVKs2m0QN7vxRs2im5MDaNCWGmcD2rvcZx"));
			final byte[] buffer = sr.generateSeed(10);
			final Base32 codec = new Base32();
			final byte[] bEncodedKey = codec.encode(buffer);
			final String encodedKey = new String(bEncodedKey);
			return encodedKey;
		} catch (NoSuchAlgorithmException ex) {
			return null;
		}
	}

	public static String getQRBarcodeURL(final String user, final String host, final String secret) {
		final String format = "https://www.google.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth://totp/%s@%s%%3Fsecret%%3D%s";
		return String.format(format, user, host, secret);
	}

	public boolean check_code(final String secret, final long code, final long timeMsec) {
		final Base32 codec = new Base32();
		final byte[] decodedKey = codec.decode(secret);
		final long t = timeMsec / 1000L / 30L;
		for (int i = -this.window_size; i <= this.window_size; ++i) {
			long hash;
			try {
				hash = verify_code(decodedKey, t + i);
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
			if (hash == code) {
				return true;
			}
		}
		return false;
	}

	private static int verify_code(final byte[] key, final long t)
			throws NoSuchAlgorithmException, InvalidKeyException {
		final byte[] data = new byte[8];
		long value = t;
		int i = 8;
		while (i-- > 0) {
			data[i] = (byte) value;
			value >>>= 8;
		}
		final SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
		final Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(signKey);
		final byte[] hash = mac.doFinal(data);
		final int offset = hash[19] & 0xF;
		long truncatedHash = 0L;
		for (int j = 0; j < 4; ++j) {
			truncatedHash <<= 8;
			truncatedHash |= (hash[offset + j] & 0xFF);
		}
		truncatedHash &= 0x7FFFFFFFL;
		truncatedHash %= 1000000L;
		return (int) truncatedHash;
	}

	public static void main(final String[] args) {
		final String secret = genSecret("testuser");
		System.out.println("secret : " + secret);
		final String key = "";
		final Boolean authcode = authcode(key, secret);
		if (authcode) {
			System.out.printf("真...........", new Object[0]);
		} else {
			System.out.printf("假.........", new Object[0]);
		}
	}
}
